package com.pronhub.luowowo.website.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.pronhub.luowowo.article.domain.*;
import com.pronhub.luowowo.article.query.TravelQuery;
import com.pronhub.luowowo.article.service.*;
import com.pronhub.luowowo.comment.domain.TravelComment;
import com.pronhub.luowowo.comment.query.TravelCommentQuery;
import com.pronhub.luowowo.comment.service.ITravelCommentService;
import com.pronhub.luowowo.excption.LoginException;
import com.pronhub.luowowo.member.domain.UserInfo;
import com.pronhub.luowowo.util.AjaxResult;
import com.pronhub.luowowo.website.web.annotation.UserToken;
import com.pronhub.luowowo.website.web.util.UMEditorUploader;
import com.pronhub.luowowo.website.web.util.UploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private ITravelCommendService travelCommendService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyCatalogService strategyCatalogService;
    @Reference
    private ITravelCommentService travelCommentService;
    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo") TravelQuery qo) {
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        //tcs  最近有谁评论了


        //1获得当前最新的评论 按照评论时间来排序
        List<TravelComment> tcs = travelCommentService.queryForCreatTimeTop10();
        model.addAttribute("tcs", tcs);

        return "travel/list";
    }

    @RequestMapping("input")
    public String input(Model model, @ModelAttribute("qo") TravelQuery qo, Long id, @UserToken UserInfo userInfo,
                        HttpServletResponse response) {
        if (userInfo==null){
            try {
                response.sendRedirect("/login.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        //dests 旅游地点 就是所有的城市  就看看你需要的深度需要
        List<Destination> destinations = destinationService.getDestsByDeep(3);
        model.addAttribute("dests",destinations);

        Travel travel=null;
        if (id != null) {
            travel = travelService.get(id);
            Long userIdForTravel = travel.getAuthor().getId();
            //少查一次数据库
            if (userIdForTravel != userInfo.getId()){
                //不是编辑自己的游记 不能编辑
                throw new LoginException("你没有这个操作的权限");
            }


            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv",travel);
        }
        return "travel/input";
    }

    //detail
    @RequestMapping("detail")
    public String detail(Model model, Long id) {
        //传过来的是游记的id 通过游记的id查出来游记的内容
        //detail
        Travel travel = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        travel.setTravelContent(content);
        model.addAttribute("detail", travel);
        //toasts
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts", toasts);
        model.addAttribute("dest", dest);
        //sds 前三的攻略文章
        List<StrategyDetail> strategyDetails = strategyDetailService.queryViewTop3(travel.getDest().getId());
        model.addAttribute("sds", strategyDetails);
        //ts前三的游记文章  广州地区的前三文章
        List<Travel> travels = travelService.getViewNumTop3(travel.getDest().getId());
        model.addAttribute("ts", travels);


        //根据游记的id去查出来改游记的所有评论
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);
        Page page = travelCommentService.query(qo);
        model.addAttribute("list", page.getContent());

        return "travel/detail";
    }
    @Value("${file.path}")
    private String filePath;
    //contentImage 图片上传的
    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile,HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserToken UserInfo userInfo){
        if (userInfo.getId()==null){
            throw new LoginException("未登录");
        }
        travel.setAuthor(userInfo);
        Long aLong = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(aLong);
    }
    //添加评论
    //commentAdd
    @RequestMapping("commentAdd")
    public String commentAdd(TravelComment comment, @UserToken UserInfo userInfo,Model model){


        comment.setUserId(userInfo.getId());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setCity(userInfo.getCity());
        comment.setUsername(userInfo.getNickname());


        //添加游记的品论到MongoDB里面


        TravelComment travelComment = travelCommentService.saveOrUpdate(comment);
        model.addAttribute("c",travelComment);//当前评论
        model.addAttribute("floor",travelCommentService.getcountByTravelId(comment.getTravelId()));
        return "travel/commentTpl";
    }

}
